﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using HM.DataAccessLayer;
using HM.DataAccessLayer.DTO;
using AutoMapper;
using System.Windows.Data;
using System.Globalization;


namespace HMViewerWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {


        public string PlayerName;
        public string FidelityLabel;
        PokerSites _currentSite = new PokerSites();
        public CoreReader  CoreReader;

        private Players _player = new Players();

        private System.Windows.Threading.DispatcherTimer _dispatcherTimer;
        public PlayerStats PlayerStats = new PlayerStats();

        public MainWindow()
        {
            InitializeComponent();


            //// Create a settings window if not in debug
            //if (_config.GetValueFromAppConfig("debug", "false") != "true")
            Window settingsWindow = new SettingsWindow();
            settingsWindow.ShowDialog();
            


            Mapper.CreateMap<PlayerStats, PlayerStats>();

            //initialisation
            InitStats();
        }

        //fonction that initialise data
        public void InitStats()
        {
         
            //getting values from settings
            string playerName="unknown";
            string siteName="??";
            _currentSite = new PokerSites();

            grid1.DataContext = PlayerStats;


            Properties.Settings settings = Properties.Settings.Default;

            switch (settings.StartWith)
            {

                case 0:
                    //pokerstars
                    playerName = settings.PlayerName_PS;
                    siteName = "PS";
                    _currentSite = PokerSites.Ps;
                    FidelityLabel = "VPP";
                    break;

                case 1:
                    //fulltilt
                    playerName = settings.PlayerName_FT;
                    siteName = "FT";
                    _currentSite = PokerSites.Ft;
                    FidelityLabel = "FTP";
                    break;
                
                case 2:
                    //winamax
                    playerName = settings.PlayerName_WNM;
                    siteName = "WNM";
                    _currentSite = PokerSites.Wnm;
                    FidelityLabel = "MILES";
                    break;

                case 3:
                    //Everest Poker
                    playerName = settings.PlayerName_EVY;
                    siteName = "EVT";
                    _currentSite = PokerSites.Evt;
                    FidelityLabel = "SP";
                    break;

                default:
                    this.Close();       //exiting
                    break;
            }

            
            lblPlayerName.Content = string.Format("{0}({1})",playerName,siteName );
            ucVpp.Titre = FidelityLabel;


            //making change if we are in debug or not
#if DEBUG
            datePicker1.SelectedDate = Convert.ToDateTime(ConfigurationManager.AppSettings["debugforcedate"]);
            datePicker1.SelectedDate = DateTime.Now;
#else
                datePicker1.SelectedDate = DateTime.Now;
                datePicker1.Visibility = Visibility.Hidden;
                lblDebug.Visibility = System.Windows.Visibility.Hidden;

#endif


            //initialising the core reader to HM DAL
            CoreReader = new CoreReader(settings.HMServerAdress, settings.HMServerPort, settings.HMServerLogin,
                                        settings.HMServerPassword,settings.HMDataBaseName);


            //getting the 
            _player = CoreReader.GetPlayerByName(playerName, _currentSite);
            if (_player != null)
            {
                //the player has been found
                //initialising the timer
                _dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
                _dispatcherTimer.Tick += new EventHandler(DispatcherTimerTick);
                _dispatcherTimer.Interval = new TimeSpan(0, 0, settings.RefreshSeconds);      //5seconds
                _dispatcherTimer.Start();
            }
            else
            {
               label7.Content=string.Format("'{0}' has not been found for this site. Exiting...", playerName);
               lblUpdateTime.Visibility = System.Windows.Visibility.Hidden;
               datePicker1.IsEnabled = false;
            }
            //UpdatePlayerStats();

            

       }

        //  System.Windows.Threading.DispatcherTimer.Tick handler
        //
        //  Updates the current seconds display and calls
        //  InvalidateRequerySuggested on the CommandManager to force 
        //  the Command to raise the CanExecuteChanged event.
        private void DispatcherTimerTick(object sender, EventArgs e)
        {
            //UpdatePlayerStatsManually();        //updating stats
            UpdatePlayerStatsDataBinding();        //updating stats
        }



        ////update the stats for the current player manually
        //public void UpdatePlayerStatsManually()
        //{

        //    try
        //    {


        //        //only updating Stats for the current day
        //        DateTime _t = datePicker1.SelectedDate.GetValueOrDefault();
        //        DateTime _tstart = new DateTime(_t.Year, _t.Month, _t.Day, 0, 0, 0);  //defining the start hour to 00:00:00
        //        DateTime _tstop = new DateTime(_t.Year, _t.Month, _t.Day, 23, 59, 59);  //defining the stop hour to 23:59:59

        //        //updating the stats   
        //        if (CoreReader != null)
        //            _playerStats = CoreReader.GetPlayerStats(_currentSite, _player.player_id, _tstart, _tstop);


        //        //PlayerStats.NbCashHands++;
        //        //lblLastUpdate.Content = DateTime.Now.ToLongTimeString();


        //        //updating using user control
        //        ucNbHands.Valeur = _playerStats.NbCashHands.ToString();
        //        ucWon.Valeur = _playerStats.AmountWon.ToString();
        //        ucRaked.Valeur = _playerStats.AmountRaked.ToString();
        //        ucVpp.Valeur = _playerStats.FidelityPointEarned.ToString();

        //        this.Title = string.Format("{0} {3}, {1} Won {2}", ucVpp.Valeur, ucRaked.Valeur, "HMViewver", FidelityLabel);





        //    }
        //    catch(Exception ex)
        //    {
        //        _dispatcherTimer.Stop();
        //        MessageBox.Show(string.Format("An error has occured : {0}", ex.Message), "Error"
        //            , MessageBoxButton.OK, MessageBoxImage.Stop);

                
        //    }



        //}


        //update the stats for the current player by databinding
        public void UpdatePlayerStatsDataBinding()
        {

            try
            {
                Debug.WriteLine("Update Timer called");

                //if the core redaer is not initialised returing
                if (CoreReader == null) return;

                //only updating Stats for the current day
                DateTime _t = datePicker1.SelectedDate.GetValueOrDefault();
                DateTime _tstart = new DateTime(_t.Year, _t.Month, _t.Day, 0, 0, 0);  //defining the start hour to 00:00:00
                DateTime _tstop = new DateTime(_t.Year, _t.Month, _t.Day, 23, 59, 59);  //defining the stop hour to 23:59:59

                //Retriving the Data from DataBase
                PlayerStats temp =  CoreReader.GetPlayerStats(_currentSite,   _player.player_id, _tstart, _tstop);

                
                ////automapping the DatabindedPlayer Objet from the temp Data Stats
                ////Mapper.Map(temp,PlayerStats);


                ////updating the ressource of the XAML window
                //PlayerStats pl =   (PlayerStats)this.windowHMStats.FindResource("pl");
                //if (pl != null)
                //{
                //    Mapper.Map(temp, pl);
                //    //pl.AmountWon++;
                //}

                //defining the new datacontext to the grid
                this.windowHMStats.grid1.DataContext = temp;
                
                


                //updating the title to )
                this.Title = string.Format("{0} {2}/{1} € Raked", ucVpp.ValeurString, ucRaked.ValeurString, FidelityLabel);
                lblUpdateTime.Content = DateTime.Now.ToLongTimeString();





            }
            catch (Exception ex)
            {
                _dispatcherTimer.Stop();
                MessageBox.Show(string.Format("An error has occured : {0}", ex.Message), "Error"
                    , MessageBoxButton.OK, MessageBoxImage.Stop);


            }



        }



        //on changing date
        private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            //UpdatePlayerStatsManually();
            UpdatePlayerStatsDataBinding();
        }




    }

    public class ValueDoubleFormatConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //if it is a string, simply return the string
            if (value is string)
                return value;

            double v = System.Convert.ToDouble(value);
            return v;
            //Debug.WriteLine("ValueFormatConverter called");
            //return v > 10000 ? v.ToString("F0") : v.ToString("F2");

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
